package com.umeox.watch.motioncapture.upload

import android.content.Context
import android.os.RemoteException
import android.util.Log
import com.umeox.watch.motioncapture.model.DataPackage
import com.umeox.watch.motioncapture.model.GsensorData
import com.umeox.watch.moto.dataservice.proxy.PullApiClientProxy
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import java.io.File
import java.io.FileWriter

class UploadManager {

    companion object {
        private const val TAG = "UploadManager"
    }

    private var fileWriter: FileWriter? = null
    private var file: File? = null

    private var dataPackage: DataPackage? = null

    private var isGathering = false

    fun init(context: Context, fileName: String) {
        Log.d(TAG, "初始化数据上传管理器")
        // 设置保存路径
        val filePath = context.externalCacheDir!!.absolutePath
        file = File(filePath, fileName)
        fileWriter = FileWriter(file)
        fileWriter?.append(
            listOf(
                "TIMESTAMP",
                "ACC_X",
                "ACC_Y",
                "ACC_Z"
            ).joinToString(",")
        )
        fileWriter?.append("\n")
        isGathering = true
    }

    fun gatherData(data: GsensorData) {
        if (!isGathering) {
            Log.d(TAG, "已停止数据采集")
            return
        }
        if (dataPackage == null) {
            Log.d(TAG, "包数据对象为空，创建包数据对象")
            dataPackage = DataPackage()
        }
        if (dataPackage?.checkFill() == true) {
            //数据已满 保存此包 创建下个包
            appendToCVS(dataPackage!!)
            Log.d(TAG, "包数据已满，创建新包数据对象")
            dataPackage = DataPackage()
        }
        dataPackage!!.fillInData(data)
    }

    private fun appendToCVS(dataPackage: DataPackage) {
        fileWriter?.append(dataPackage.getData())
        fileWriter?.append("\n")
    }

    fun stopGather() {
        Log.d(TAG, "停止采集数据")
        //保存数据
        fileWriter?.flush()
        fileWriter?.close()
        //初始化
        fileWriter = null
        dataPackage = null
        isGathering = false
        //上传服务器
        Log.d(TAG, "上传文件到服务器")
        uploadFile()
    }

    @Throws(RemoteException::class)
    private fun uploadFile() {
        file?.let {
            val filePath = it.absolutePath
            Log.d(TAG, "uploadFile: filePath = $filePath")
            GlobalScope.launch(Dispatchers.IO) {
                PullApiClientProxy.fetchBinder()
                    .uploadFileByFileType(filePath, 999)
            }
        }
        file = null
    }


}